// pages/game/play.js
var gmapi = require('../../utils/gameapi.js');
const app = getApp();
Page({
  /**
   * 页面的初始数据
   * endplayno:成绩提交开关
   */
  data: {
    classid: '',
    musicsrc: app.globalData.bgm1,
    indexplaymuiscno: app.globalData.playmuiscno,
    musicsrc3: app.globalData.bgm3,
    musicsrc4: app.globalData.bgm4,
    musicsrc5: app.globalData.bgm5,
    musicsrc6: app.globalData.bgm6,
    tipslost: 'none',
    tipswin: 'none',
    gmanimation: '',
    endplayno: 0,
    textright: 0,
    textmun: 0,
    animationtext: '',
    "overtime": '呀！超时啦，集中注意力~',
    "Success": '恭喜您，挑战成功！',
    "Continue": '继续挑战',
    "again": '再玩一次',
    classid: 0,
    token: '',
    reg: {
      "code": "200",
      "msg": "操作成功",
      "data": {
        "originalText": [
          "为你圆梦,替你买单"
        ],
        "fallShuffle": 0,
        "recovertime": 15,
        "gameplaylogId": "b745a7b67d104e099084c4504468db43",
        "randomText": [
          "你圆为梦,你买单替"
        ],
        "showShuffle": 0,
        "randomcontent": 2,
        "memorytime": 5
      },
      "remark": null
    },
    click1: 'clicktext1',
    gmcsslist: [
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ]
    ],
    gmlist: [
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ]
    ],
    arrmain: [
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ]
    ],
    test: Array[8 * 8],
    listpx: [],
    listpy: [],
    gmtext: '想',
    timer: '', //定时器名字
    countDownNum: '100' //倒计时初始值
  },
  clicktext1(e) {

  },
  /**
   * 填字函数
   */
  clicktext(e) {
    var that = this;
    var sz = '';
    if (e.target.dataset.text == "") {

    } else {
      if (that.data.animationtext == that.data.gmtextlist[e.target.dataset.px][e.target.dataset.py] && that.data.gmlist[e.target.dataset.px][e.target.dataset.py] == "") {
        that.playeffect(3);
        sz = gmapi.gmsetArray('gmlist', e.target.dataset.px, e.target.dataset.py);
        that.setData({
          textright: that.data.textright + 1,
          [sz]: that.data.animationtext
        })
        if (that.data.textright < that.data.textmun) {
          that.setData({
            animationtext: that.data.goplaytext[that.data.textright]
          })
          that.gmanimationres(-100)
          that.setData({
            timeani: setInterval(function() {
              that.gmanimationdown(100);
              clearInterval(that.data.timeani);
            }, 100)
          })
        } else {
          console.log('胜利!!');
          that.setData({
            endplayno: that.data.endplayno + 1
          })
          that.endplay();
          //console.log(that.data.textmun)
        }
      } else {
        that.playeffect(4);
        if (that.data.gmlist[e.target.dataset.px][e.target.dataset.py] == '') {
          sz = gmapi.gmsetArray('gmcsslist', e.target.dataset.px, e.target.dataset.py);
          that.setData({
            [sz]: that.data.gmtext,
            click1: 'clicktext1',
            timererr: setInterval(function() {
              that.setData({
                [sz]: '',
                click1: 'clicktext'
              })
              clearInterval(that.data.timererr);
            }, 1000)
          });
          //console.log("错了")
        }
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    if (that.data.classid == 0) {
      that.setData({
        classid: options.id
      })
    }
    wx.request({
      url: app.globalData.urlapi + '/splicingGame/getGameQuestion2',
      method: 'GET',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': app.globalData.token
      },
      data: {
        ordernumber: that.data.classid
      },
      success: function(res) {
        //var reglist = gmapi.gamestart(res.data);
        //var reg = res.data;reg

        console.log(res.data);
        if (res.data.code == 200) {
          var reglist = gmapi.gamestart(res.data);
          var goplaytext = gmapi.gmtextdown(res.data);
          var reg = res.data;
          that.setData({
            reglist,
            goplaytext,
            reg
          })
          var gmtextlist = [
            ["", "", "", "", "", "", "", "", ],
            ["", "", "", "", "", "", "", "", ],
            ["", "", "", "", "", "", "", "", ],
            ["", "", "", "", "", "", "", "", ],
            ["", "", "", "", "", "", "", "", ],
            ["", "", "", "", "", "", "", "", ],
            ["", "", "", "", "", "", "", "", ],
            ["", "", "", "", "", "", "", "", ]
          ];
          for (let i = 0; i < reglist.length; i++) {
            for (let j = 0; j < reglist[i].length; j++) {
              gmtextlist[reglist[i][j].px][reglist[i][j].py] = reglist[i][j].text;
            }
          }
          that.setData({
            gmtextlist,
            textmun: goplaytext.length
          })
          that.gopaly();
          //console.log("文字顺出顺序:" + goplaytext);
        } else {
          wx.redirectTo({
            url: '../index/index'
          })
          //console.log("文字顺出顺序:" + goplaytext);
        }

      }
    })
  },
  /**
   * 字体掉落
   */
  gmanimationdown: function(a) {
    this.gmanimation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'linear',
      delay: 0
    })
    this.gmanimation.translateY(a).step()
    this.setData({
      //输出动画
      gmanimation: this.gmanimation.export()
    })

  },
  /**
   * 字体复位
   */
  gmanimationres: function(a) {
    this.gmanimation = wx.createAnimation({
      duration: 100,
      timingFunction: 'step-start',
      delay: 0
    })
    this.gmanimation.translateY(a).step()
    this.setData({
      //输出动画
      gmanimation: this.gmanimation.export()
    })

  },
  /**
   * 计时器
   */
  countDown: function(playtime) {
    //console.log('进入计时器,倒计时数值:' + playtime);
    let that = this;
    let countDownNum1 = 100; //获取倒计时初始值

    let cn = 100 / playtime;
    //如果将定时器设置在外面，那么用户就看不到countDownNum的数值动态变化，所以要把定时器存进data里面
    that.setData({
      countDownNum: 100,
      timerprogress: setInterval(function() { //这里把setInterval赋值给变量名为timer的变量
        //每隔一秒countDownNum就减一，实现同步
        countDownNum1 = countDownNum1 - cn;
        //然后把countDownNum存进data，好让用户知道时间在倒计着
        that.setData({
          countDownNum: countDownNum1,
        })
        //在倒计时还未到0时，这中间可以做其他的事情，按项目需求来
        if (countDownNum1 < 1) {
          // console.log('清除倒计时,倒计时数值:' + countDownNum1);
          that.setData({
            countDownNum: 100
          })
          //这里特别要注意，计时器是始终一直在走的，如果你的时间为0，那么就要关掉定时器！不然相当耗性能
          //因为timer是存在data里面的，所以在关掉时，也要在data里取出后再关闭
          clearInterval(that.data.timerprogress);

          //关闭定时器之后，可作其他处理codes go here
        }
      }, 1000)
    })
  },
  countDown1: function(playtime) {
    //console.log('进入计时器,倒计时数值:' + playtime);
    let that = this;
    let countDownNum1 = 100; //获取倒计时初始值

    let cn = 100 / playtime;
    //如果将定时器设置在外面，那么用户就看不到countDownNum的数值动态变化，所以要把定时器存进data里面
    that.setData({
      countDownNum: 100,
      timerprogress1: setInterval(function() { //这里把setInterval赋值给变量名为timer的变量
        //每隔一秒countDownNum就减一，实现同步
        countDownNum1 = countDownNum1 - cn;
        //然后把countDownNum存进data，好让用户知道时间在倒计着
        that.setData({
          countDownNum: countDownNum1,
        })
        //在倒计时还未到0时，这中间可以做其他的事情，按项目需求来
        if (countDownNum1 < 1) {
          //console.log('清除倒计时,倒计时数值:' + countDownNum1);
          that.setData({
            countDownNum: 100
          })
          //这里特别要注意，计时器是始终一直在走的，如果你的时间为0，那么就要关掉定时器！不然相当耗性能
          //因为timer是存在data里面的，所以在关掉时，也要在data里取出后再关闭
          clearInterval(that.data.timerprogress1);

          //关闭定时器之后，可作其他处理codes go here
        }
      }, 1000)
    })
  },
  /**
   * 开始游戏
   */
  gopaly: function() {
    var sz;
    var that = this;
    let i = 0;
    let j = 0;
    let t = 1;
    var gotime = 100 / that.data.reg.data.memorytime;
    //console.log("gopaly:" + a);
    if (that.data.reg.data.fallShuffle == 2) {
      var a = gmapi.gmgoplay1(that.data.reglist, that.data.reg);
      if (this.audioCtx != null && app.globalData.playmuiscno == 1) {
        that.audioCtx.play();
      }
      if (a.length == 2) {
        that.setData({
          timer1: setInterval(function() {
            if (i < a.length) {
              if (j < a[i].length) {
                sz = gmapi.gmsetArray("gmlist", a[i][j].px, a[i][j].py)
                that.setData({
                  [sz]: a[i][j].text
                })
                j++;
              } else if (j >= a[i].length) {
                //console.log("T倒计时:" + t);

                if (t % (that.data.reg.data.memorytime + 1) != 0) {
                  t = t + 0.5;
                  if (t % 1 != 0) {
                    that.setData({
                      countDownNum: that.data.countDownNum - gotime
                    })
                  }
                } else {
                  var gmlist = [
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ]
                  ];
                  that.setData({
                    gmlist,
                    countDownNum: 100
                  })
                  i++;
                  j = 0;
                  t = 1;
                }
              }
            } else {
              that.setData({
                click1: 'clicktext',
                animationtext: that.data.goplaytext[that.data.textright]
              })
              that.gmanimationdown(100);
              that.countDown1(that.data.reg.data.recovertime);
              that.setData({
                timer3: setInterval(function() {

                  that.setData({
                    click1: 'clicktext1'
                  })
                  if (that.data.endplayno == 0) {
                    that.endplay();
                  }
                  clearInterval(that.data.timer3);
                }, that.data.reg.data.recovertime * 1000)
              });
              that.audioCtx.pause();
              //console.log(that.data.gmlist)
              clearInterval(that.data.timer1);
            }

          }, 500)
        })
      } else {
        that.setData({
          timer1: setInterval(function() {
            if (i < a.length) {
              if (j < a[i].length) {
                sz = gmapi.gmsetArray("gmlist", a[i][j].px, a[i][j].py)
                that.setData({
                  [sz]: a[i][j].text
                })
                j++;
              } else if (j >= a[i].length && i % 2 != 0) {
                // console.log("T倒计时:" + t);
                if (t % (that.data.reg.data.memorytime + 1) != 0) {
                  t = t + 0.5;
                  if (t % 1 != 0) {
                    that.setData({
                      countDownNum: that.data.countDownNum - gotime
                    })
                  }
                } else {
                  var gmlist = [
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ],
                    ["", "", "", "", "", "", "", "", ]
                  ];
                  that.setData({
                    gmlist,
                    countDownNum: 100
                  })
                  i++;
                  j = 0;
                  t = 1;
                }
              } else if (j >= a[i].length && i % 2 == 0) {
                i++;
                j = 0;
              }
            } else {
              that.setData({
                click1: 'clicktext',
                animationtext: that.data.goplaytext[that.data.textright]
              })
              that.gmanimationdown(100);
              that.countDown1(that.data.reg.data.recovertime);
              that.setData({
                timer3: setInterval(function() {

                  that.setData({
                    click1: 'clicktext1'
                  })
                  if (that.data.endplayno == 0) {
                    that.endplay();
                  }
                  clearInterval(that.data.timer3);
                }, that.data.reg.data.recovertime * 1000)
              });
              that.audioCtx.pause();
              //console.log(that.data.gmlist)
              clearInterval(that.data.timer1);
            }

          }, 500)
        })
      }
    } else {
      var a = gmapi.gmgoplay(that.data.reglist, that.data.reg);
      if (this.audioCtx != null && app.globalData.playmuiscno == 1) {
        that.audioCtx.play();
      }
      that.setData({
        timer1: setInterval(function() {
          if (i < a.length) {
            sz = gmapi.gmsetArray("gmlist", a[i].px, a[i].py)
            that.setData({
              [sz]: a[i].text
            })
            i++;
          } else {
            var time2 = 0;
            // console.log(that.data.gmlist)
            var gmlist = [
              ["", "", "", "", "", "", "", "", ],
              ["", "", "", "", "", "", "", "", ],
              ["", "", "", "", "", "", "", "", ],
              ["", "", "", "", "", "", "", "", ],
              ["", "", "", "", "", "", "", "", ],
              ["", "", "", "", "", "", "", "", ],
              ["", "", "", "", "", "", "", "", ],
              ["", "", "", "", "", "", "", "", ]
            ];
            that.countDown(that.data.reg.data.memorytime);
            that.setData({
              timer2: setInterval(function() {
                that.setData({
                  gmlist,
                  click1: 'clicktext',
                  animationtext: that.data.goplaytext[that.data.textright]
                })
                that.gmanimationdown(100);
                time2++;
                that.countDown1(that.data.reg.data.recovertime);
                that.setData({
                  timer3: setInterval(function() {

                    that.setData({
                      click1: 'clicktext1'
                    })
                    if (that.data.endplayno == 0) {
                      that.endplay();
                    }
                    clearInterval(that.data.timer3);
                  }, that.data.reg.data.recovertime * 1000)
                });
                that.audioCtx.pause();
                clearInterval(that.data.timer2);
                // console.log(that.data.gmlist)
              }, that.data.reg.data.memorytime * 1000)
            })
            clearInterval(that.data.timer1);
          }
        }, 500)
      })

    }



  },
  /**
   * 结束游戏提交成绩
   */
  endplay: function() {
    var that = this;
    // console.log(that.data.textright);
    wx.request({
      url: app.globalData.urlapi + '/splicingGame/commitGame2',
      method: 'GET',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': app.globalData.token
      },
      data: {
        gameplaylogId: that.data.reg.data.gameplaylogId,
        correctcount: that.data.textright
      },
      success: function(res) {
        //console.log('提交成绩:' + res)
        if (res.data.code == 200) {
          if (res.data.data.status) {
            that.playeffect(6)
            that.setData({
              tipswin: '',
              money_s: res.data.data.award
            })
          } else {
            that.playeffect(5)
            that.setData({
              tipslost: ''
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            success: function(res) {
              if (res.confirm) {
                //console.log('弹框后点取消')
              } else {
                //console.log('弹框后点取消')
              }
            }
          })
        }
      }
    })
  },
  /**
   * 失败tips相关操作
   */
  tipslostclose: function() {
    var that = this;
    that.setData({
      tipslost: 'none'
    })
    wx.redirectTo({
      url: '../index/index'
    })
  },
  tipslostagain: function() {
    var that = this;
    var a = [
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ],
      ["", "", "", "", "", "", "", "", ]
    ];
    clearInterval(that.data.timer1);
    clearInterval(that.data.timer2);
    clearInterval(that.data.timer3);
    clearInterval(that.data.timerprogress);
    clearInterval(that.data.timererr);
    clearInterval(that.data.timerani);
    that.setData({
      gmtextlist: a,
      gmlist: a,
      gmcsslist: a,
      arrmain: a,
      tipslost: 'none',
      countDownNum: 100,
      animationtext: '',
      endplayno: 0,
      textright: 0,
      textmun: 0
    })
    //console.log(that.data.arrmain);
    that.gmanimationres(-100);
    that.onLoad()
  },
  /**
   * 赢了进入下一关
   */
  tipswingoplay: function() {
    var that = this;
    // console.log("进来了")

    wx.redirectTo({
      url: '../game2/play?id=' + (that.data.classid - 1 + 2)
    });
  },
  /**
   * 音乐控制
   */
  playmuisc: function() {
    var that = this;
    if (app.globalData.playmuiscno == 1) {
      this.audioCtx.pause();
      that.setData({
        indexplaymuiscno: 0
      })
      app.globalData.playmuiscno = 0;
    } else {
      this.audioCtx.play();
      that.setData({
        indexplaymuiscno: 1
      })
      app.globalData.playmuiscno = 1;
    }
  },
  audioPlay: function() {
    this.audioCtx.play()
  },
  audioPause: function() {
    this.audioCtx.pause()
  },
  /**
   * 背景音
   */
  playeffect: function(a) {
    var that = this;
    if (app.globalData.playmuiscno == 1) {
      if (a == 3) {

        that.audioCtx3.seek(0);
        that.audioCtx3.play();
      } else if (a == 4) {

        that.audioCtx4.seek(0);
        that.audioCtx4.play();
      } else if (a == 5) {

        that.audioCtx5.seek(0);
        that.audioCtx5.play();
      } else if (a == 6) {

        that.audioCtx6.seek(0);
        that.audioCtx6.play();
      }

    }
  },
  /**gmlist
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.audioCtx = wx.createAudioContext('myAudio');
    this.audioCtx3 = wx.createAudioContext('myAudio3');
    this.audioCtx4 = wx.createAudioContext('myAudio4');
    this.audioCtx5 = wx.createAudioContext('myAudio5');
    this.audioCtx6 = wx.createAudioContext('myAudio6');
    if (this.audioCtx != null && app.globalData.playmuiscno == 1) {
      this.audioCtx.play()
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.audioCtx != null && app.globalData.playmuiscno == 1) {
      this.audioCtx.play()
    }
    var that = this;
    that.setData({
      indexplaymuiscno: app.globalData.playmuiscno
    })
    //this.countDown(9);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.audioCtx.pause();
    wx.redirectTo({
      url: '../index/index'
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var that = this;
    clearInterval(that.data.timer1);
    clearInterval(that.data.timer2);
    clearInterval(that.data.timer3);
    clearInterval(that.data.timerprogress);
    clearInterval(that.data.timererr);
    clearInterval(that.data.timerani);
    this.audioCtx.pause()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var obj = {
      path: '/pages/index/index'
    }

    return obj;
  }
})